package com.campus.customer.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.customer.bean.address.AddressBean;
import com.campus.customer.entity.Address;
import com.campus.customer.mapper.AddressMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 收货地址表 服务实现类
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-04-02
 */
@Service
public class AddressService extends ServiceImpl<AddressMapper, Address> {

    public List<Address> getUserAddressList(Integer userId) {
        List<Address> list = baseMapper.selectList(Wrappers.<Address>lambdaQuery().eq(Address::getUserId, userId));

        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveUserAddress(AddressBean addressBean) {
        Address address = new Address();
        BeanUtil.copyProperties(addressBean, address);
        if(address.getIsDefault()) {
            //如果新增地址设为默认，则原来该用户已有的地址需要设为非默认
            update(Wrappers.<Address>lambdaUpdate().eq(Address::getUserId, addressBean.getUserId()).eq(Address::getIsDefault, true).set(Address::getIsDefault, false));
        }
        saveOrUpdate(address);
    }
}
